package com.xiebishe.mylibrary.common.mvvm;

import androidx.lifecycle.LifecycleOwner;

/**
 * @class 包含状态的livedata
 * @describe
 */
public class StateLiveData<T> extends DefaultLiveData<T> {
    private enum State {
        SUCCESS, ERROR, EMPTY
    }

    private DefaultLiveData<State> stateLiveData = new DefaultLiveData<>();

    private EventLiveData<Boolean> loadingLiveData = new EventLiveData<>();

    public void postStartLoading() {
        loadingLiveData.postValue(true);
    }

    public void postStopLoading() {
        loadingLiveData.postValue(false);
    }

    public void postValueAndSuccess(T value) {
        stateLiveData.postValue(State.SUCCESS);
        postValue(value);
    }

    public void postError() {
        stateLiveData.postValue(State.ERROR);
    }

    public void postEmpty() {
        stateLiveData.postValue(State.EMPTY);
    }


    public void observe(LifecycleOwner lifecycleOwner, ValueAndStateChangeListener<T> listener) {
        this.observe(lifecycleOwner, listener::onValueUpdate);
        this.loadingLiveData.observe(lifecycleOwner, loading -> {
            if (loading) {
                listener.onLoadingStart();
            } else {
                listener.onLoadingStop();
            }
        });
        this.stateLiveData.observe(lifecycleOwner, state -> {
            switch (state) {
                case EMPTY:
                    listener.onEmpty();
                    break;
                case SUCCESS:
                    listener.onSuccess();
                    break;
                case ERROR:
                    listener.onError();
                    break;
            }
        });
    }

    public interface ValueAndStateChangeListener<T> {
        void onValueUpdate(T value);

        void onSuccess();

        void onEmpty();

        void onError();

        void onLoadingStart();

        void onLoadingStop();

    }
}
